package gis.auth;

import bean.ltecover.Building;
import gis.algorithm.GeoPoint;
import gis.algorithm.GeoUtils;
import gis.common.GisConfig;
import gis.core.utils.CoreUtils;
import gis.core.utils.DesUtil;
import gis.core.utils.TimeUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by Xiaobing on 2016/9/21.
 */
public class CommonAuth {
    private static Logger logger = LoggerFactory.getLogger(CommonAuth.class);

    public boolean authLicense() {
        if (isAuth()) {
            return true;
        }

        logger.error("尝试重新加载授权文件!");
        String path = GisConfig.GetInstance().getBasePath() + "files/license.bat";
        String license = "";
        InputStreamReader stream = null;
        BufferedReader reader = null;
        try {
            stream = new InputStreamReader(new FileInputStream(path), "UTF-8");
            reader = new BufferedReader(stream);
            String line = null;

            while ((line = reader.readLine()) != null) {
                license = line;
                break;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            CoreUtils.close(reader, stream);
        }

        String le = "";
        try {
            le = DesUtil.decrypt(license);
            String[] s = StringUtils.splitPreserveAllTokens(le, "_");

            if (s == null || s.length != 2) {
                //当前时间
                if (!s[0].equals(GisConfig.GetInstance().getArea())) {
                    throw new Exception("授权码错误！");
                }
                SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHH");
                String key = df.format(new Date());
                if (!s[1].equals(key)) {
                    throw new Exception("授权码已过期失效！");
                }
                if (Integer.parseInt(s[2]) < 0 || Integer.parseInt(s[2]) > 40) {
                    throw new Exception("授权码日期错误！");
                }
                GisConfig.GetInstance().setLicense(Integer.parseInt(s[2]));
                GisConfig.GetInstance().setLicenseDate(Integer.parseInt(key));

                String basePath = GisConfig.GetInstance().getBasePath() + "files/log.txt";
                File file = new File(basePath);
                if (file.exists()) {
                    file.delete();
                }
                FileOutputStream out = new FileOutputStream(file);
                OutputStreamWriter osw = new OutputStreamWriter(out, "UTF-8");
                BufferedWriter bw = new BufferedWriter(osw);

                GisConfig.GetInstance().setTimelog(Integer.parseInt(key));
                String txt = DesUtil.encrypt(key + "_" + GisConfig.GetInstance().getLicense(), GisConfig.GetInstance().getArea() + GisConfig.GetInstance().getArea());
                bw.write(txt);
                bw.close();
                out.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("授权出错", e);
            String basePath = GisConfig.GetInstance().getBasePath() + "files/log.txt";
            File file = new File(basePath);
            if (file.exists()) {
                file.delete();
            }
            return false;
        }
        return true;
    }

    public boolean isAuth() {
        /*try {
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHH");
            Date date = new Date();
            int key = Integer.parseInt(df.format(date));
            if (key < GisConfig.GetInstance().getTimelog()) {
                GisConfig.GetInstance().setTimelog(Integer.MAX_VALUE);
                throw new Exception("验证授权出错，系统时间出错，尝试修改系统时间！");
            }
            if (key > GisConfig.GetInstance().getTimelog()) {
                String basePath = GisConfig.GetInstance().getBasePath() + "files/log.txt";
                File file = new File(basePath);
                InputStreamReader stream = null;
                BufferedReader reader = null;
                String oldkey = "";
                String line = null;
                try {
                    stream = new InputStreamReader(new FileInputStream(basePath), "UTF-8");
                    reader = new BufferedReader(stream);

                    while ((line = reader.readLine()) != null) {
                        oldkey = line;
                        break;
                    }
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                    throw e;
                } finally {
                    CoreUtils.close(reader, stream);
                }
                String[] log = StringUtils.splitPreserveAllTokens(DesUtil.decrypt(oldkey, GisConfig.GetInstance().getArea() + GisConfig.GetInstance().getArea()), "_");
                if (Integer.parseInt(log[1]) != GisConfig.GetInstance().getLicense() || key < Integer.parseInt(log[0])) {
                    throw new Exception("授权参数错误");
                }
                long diff = date.getTime() - TimeUtils.stringConvertDate(GisConfig.GetInstance().getLicenseDate() + "", "yyyyMMddHH").getTime();
                long days = diff / (1000 * 60 * 60 * 24);

                if (days > (GisConfig.GetInstance().getLicense() - 2)) {
                    throw new Exception("授权已过期");
                } else {
                    FileWriter a = new FileWriter(basePath);
                    BufferedWriter b = new BufferedWriter(a);
                    String txt = DesUtil.encrypt(key + "_" + GisConfig.GetInstance().getLicense(), GisConfig.GetInstance().getArea() + GisConfig.GetInstance().getArea());
                    b.write(txt);
                    b.close();
                    a.close();

                    GisConfig.GetInstance().setTimelog(key);
                }
            }
        } catch (Exception e) {
            logger.error("检查授权出错，" + e);
            return false;
        }*/

        return true;
    }
}
